package particle;

import java.io.File;  
import java.util.ArrayList;
import java.util.Stack;

import javax.xml.parsers.SAXParser;  
import javax.xml.parsers.SAXParserFactory;  
  

import org.xml.sax.Attributes;  
import org.xml.sax.SAXException;  
import org.xml.sax.helpers.DefaultHandler;  
  
public class PlistParser {  
	
	private ArrayList<String> key = new ArrayList<String>();
	private ArrayList<String> value = new ArrayList<String>();
    
    PlistParser(String filename){
    	SAXParserFactory factory = SAXParserFactory.newInstance();  
    	SAXParser parser;
    	try {
    		parser = factory.newSAXParser();
    		parser.parse(new File(filename), new ListHandler());
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }  
    
    public double getProperty(int propertyId){
    	double res = 0;
    	try{
    		res = Double.parseDouble((value.get(propertyId)));
    	} catch(Exception e){
    		e.printStackTrace();
    	}
    	return res;
    }
    
    public String getTexture(){
    	return value.get(Properties.TEXTURE_NAME);
    }
  
    private class ListHandler extends DefaultHandler {  
    	
    	private long time;
    	private Stack<String> stack = new Stack<String>(); 
    	
    	@Override  
    	public void startDocument() throws SAXException {
    		time = System.currentTimeMillis();
    	}  
      
    	@Override  
    	public void endDocument() throws SAXException {  
    		time -= System.currentTimeMillis();
    		System.out.println("----parse file finished-----\n"
    				+ "using:"+(-time) + "ms.");  
    	}  
      
    	@Override  
    	public void startElement(String uri, String localName, String qName,  
    		Attributes attributes) throws SAXException {
    		stack.push(qName);
    	}  
      
    	@Override  
    	public void endElement(String uri, String localName, String qName)  
            throws SAXException {  
    		stack.pop();
    	}
    	
    	@Override
    	public void characters(char[] ch, int start, int length)  
                throws SAXException {  
    		
    		String tag = stack.peek();
    		
            if("key".equals(tag)) {  
                key.add(new String(ch, start,length));  
            }  
            else if("real".equals(tag) || "integer".equals(tag) || "string".equals(tag)) {  
                value.add(new String(ch, start, length));  
            }  
        }  
    }
}  